package com.yupi.springbootinit.job.once;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.yupi.springbootinit.esdao.PostEsDao;
import com.yupi.springbootinit.model.entity.Post;
import com.yupi.springbootinit.service.PostService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 获取初始帖子列表
 * @author njy
 * @date 2023/5/1 20:56
 */
//取消注释后，每次启动springBoot 项目会执行一次run方法
//@Component
@Slf4j
public class FetchInitPostList implements CommandLineRunner {

    @Autowired
    private PostService postService;

    @Override
    public void run(String... args) throws Exception {
        //获取数据
        String json="{\"current\":1,\"pageSize\":8,\"sortField\":\"createTime\",\"sortOrder\":\"descend\",\"category\":\"文章\",\"reviewStatus\":1}";
        String url="https://www.code-nav.cn/api/post/search/page/vo";

        String result= HttpRequest
                .post(url)
                .body(json)
                .execute()
                .body();
//        System.out.println("result = " + result);
        //转换对象
        Map<String,Object> map= JSONUtil.toBean(result,Map.class);
        JSONObject data = (JSONObject) map.get("data");
        JSONArray records = (JSONArray) data.get("records");
//        System.out.println("records = " + records);
        List<Post> list=new ArrayList<>();
        for (Object record : records) {
            JSONObject tempRecord= (JSONObject) record;
            JSONArray tags = (JSONArray) tempRecord.get("tags");
            Post post = Post.builder()
                    .title(tempRecord.getStr("title"))
                    .content(tempRecord.getStr("content"))
                    .tags(JSONUtil.toJsonStr(tags.toList(String.class)))
                    .userId(1L)
                    .build();
            list.add(post);
        }
//        System.out.println(list);
        //数据入库
        boolean b = postService.saveBatch(list);
        if(b){
            log.info("初始化帖子列表成功,条数={}",list.size());
        }else {
            log.error("初始化帖子失败！！！");
        }
    }
}
